package com.homelock.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.homelock.common.util.HttpClientHelper;
import com.homelock.dto.IOTResp;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@SuppressWarnings("deprecation")
@Configuration
public class IotRegisterLockConfig {

    private static final Logger logger = LoggerFactory.getLogger(IotRegisterLockConfig.class);


    @Autowired
    private HttpClientHelper httpClientHelper;

    /**
     * IOT服务IP
     */
    @Value("${iot.server.ip}")
    private String ip;
    /**
     * IOT服务端口
     */
    @Value("${iot.server.port}")
    private String port;

    /**
     * IOT 注册接口地址
     */
    @Value("${iot.server.request.lockregister}")
    private String lockregisterRequest;
    @Value(("${iot.server.partnercode}"))
    private String partnerCode;

    private static final String APPEND_SYM = ":";

    /**
     * 参数
     */
    private static final String SUS_PARAM_SOURCEID = "sourceId";  // 合作id
    private static final String SUS_PARAM_IMEI = "imei";  //设备imei
    private static final String SUS_PARAM_NBDEVID = "nbDevId";   //设备code

    /**
     * 门锁注册请求
     * undo 失败之后需要进行缓存。。还未做
     * 请求3次机制还未做
     * @return
     */
    public IOTResp requestForLockRegister(String imei,String devId,Long sourceId){
        if(StringUtils.isBlank(imei) || StringUtils.isBlank(devId)){
            logger.error("IOT注册门锁失败：自检参数不完整");
            return null;
        }
        IOTResp resp = null;
        try {
            String result = httpClientHelper.post(querySuscribeUrl(), queryParams(imei,devId), null);
            logger.info("注册接口返回：" + result);
            if (StringUtils.isNotEmpty(result)) {
                // 接口失败则去掉转义字符以及前后双引号
                result = StringEscapeUtils.unescapeJava(result);
                if(result.startsWith("\"") && result.endsWith("\"")) {
                    result = result.substring(1, result.length() - 1);
                }
                resp = new ObjectMapper().readValue(result, IOTResp.class);
                if(resp.getStatus() == IOTResp.SUCCESS){
                    logger.info("门锁注册IOT平台成功："+result);
                }else{
                    logger.info("门锁注册IOT平台失败："+result);
                }
            }else{
                logger.info("门锁注册IOT平台失败,返回值为空");
            }
        }catch (Exception e){
            logger.error("门锁注册IOT平台失败:"+e.getMessage());
        }
        return resp;
    }



    /**
     * 获取门锁注册接口
     * @return
     */
    private  String querySuscribeUrl(){
        String suscribeUrl = new StringBuffer(ip).append(APPEND_SYM).append(port).append(lockregisterRequest).toString();
        logger.info("注册的请求接口："+suscribeUrl);
        return suscribeUrl;
    }

    private HashMap<String,Object> queryParams(String imei,String devId){
        HashMap<String,Object> params = new HashMap<>();
        params.put(SUS_PARAM_SOURCEID,partnerCode);  // partnercode参数
        params.put(SUS_PARAM_IMEI,imei);
        params.put(SUS_PARAM_NBDEVID, devId);
        return params;
    }

}
